package com.lagou.controller;

import com.lagou.api.service.IpService;
import com.lagou.api.service.MonitorService;
import com.lagou.util.NetworkUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@RestController
public class DubboWebController {

    @Reference
    private IpService ipService;
    @Reference
    private MonitorService monitorService;

    @RequestMapping("/ipMonitor")
    @ResponseBody
    public String ipMonitor(HttpServletRequest httpServletRequest) throws IOException {
        String ipAddress = NetworkUtil.getIpAddress(httpServletRequest);
        ipService.service(ipAddress);//这里IP是为了和拦截器中获取的ip比较,看是否相同
        return "success"+ipAddress;
    }

    @RequestMapping("/tpMonitor")
    @ResponseBody
    public String TPMonitor() throws InterruptedException {
        ThreadPoolExecutor threadPoolExecutor = createThreadPoolExecutor();
        System.out.println("=========Input something on console for starting invoke");
        for (int i = 0 ;i<=2000 ;i++) {
            Thread.sleep(8);
            threadPoolExecutor.submit(() -> {
                try {
                    //调用testingOne
                    monitorService.methodA("A");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
            threadPoolExecutor.submit(() -> {
                try {
                    //调用testingOne
                    monitorService.methodB("B");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
            threadPoolExecutor.submit(() -> {
                try {
                    //调用testingOne
                    monitorService.methodC("B");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

        }
        return "success";
    }
    public static ThreadPoolExecutor createThreadPoolExecutor() {
        int corePoolSize = 50;
        int maximumPoolSize = 50;
        long keepAliveTime = 60;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);

        return new ThreadPoolExecutor
                (corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, (r, executor)
                        -> System.out.println("======Too many requests do abort"));
    }

}
